/*
 * Copyright (c) 2021 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import router from '@system.router'
import dd from '@ohos.data.distributedData';
import prompt from '@system.prompt';

export default {
    data: {
        title: "Hello World",
        //保存输入框中输入的结果
        result: "",
        //输入提交的算式结果
        commitStr:"",
        image1: "",
        image2: "",
        image3: "",
        image4: "",
        displayimg: false,
        gameOver: false,
        images: [
            "common/images/secret.png",
            "common/images/A.png",
            "common/images/2.png",
            "common/images/3.png",
            "common/images/4.png",
            "common/images/5.png",
            "common/images/6.png",
            "common/images/7.png",
            "common/images/8.png",
            "common/images/9.png",
            "common/images/10.png",
            "common/images/J.png",
            "common/images/Q.png",
            "common/images/K.png"
        ],
        numList:[],
    },
    kv: {},
    kvm: {},
    onInit() {
//        this.title = this.$t('strings.world');
        console.log("gyf onInit");
        this.onopen();
// function test code
//        let list = this.getNums("(10+2)*2+3");
//        console.log("gyf list  = " + list);
//        if (this.isSameNums(list)) {
//            console.log("gyf isSameNums true");
//        } else {
//            console.log("gyf isSameNums false");
//        }
//        console.log("gyf onInit end");

    },

    onBack: function () {
        router.replace({
            uri: "pages/index/index"
        })
    },

    getRandom: function (Min,Max){
        var Range = Max - Min;
        var Rand = Math.random();
        var num = Min + Math.round(Rand * Range); //四舍五入
        return num;
    },

    //根据输入答案中的字符串，提取出其中的数字,返回字符串的列表，数字从小到大排序
    getNums: function (result) {
        console.log("gyf getNums")
        var arr = result.match(/\d+/g);
        var intArr = arr.map(item => {return parseInt(item)});
        intArr.sort(function (a, b) {
            return a-b;
        });
        console.log("gyf getNumber result: " + intArr);
        return intArr;
    },

    //将输入结果中的数字和扑克牌对应数字(numList中的数字)比较，是否一致
    isSameNums: function (result) {
        console.log("gyf isSameNums");
        //将result中的数字提出取来，存放在list中
        console.log("gyf isSameNums this.getNums(result).toString() = " + this.getNums(result).toString());
        console.log("gyf isSameNums this.numList.toString() = " + this.numList.toString());
        if (this.getNums(result).toString() == this.numList.toString()) {
            console.log("gyf isSameNums 111")
            return true;
        } else {
            console.log("gyf isSameNums 222")
            return false;
        }
    },

    checkResult: function (result) {
        console.log("gyf checkResult eval result = " + eval(result))
        //得数等于24，并且四个数字和给出的四张扑克牌对应的数字一致
        if (eval(result) == 24 && this.isSameNums(result)) {
            //gameOver为true，代表游戏结束。
            this.gameOver = true;
            return true;
        } else {
            return false;
        }
    },

    onopen: function() {
        this.kv = null;
        let that = this;

        try {
            const kvManagerConfig = {
                bundleName : 'com.view.distrubuted24game',
                userInfo : {
                    userId : '0',
                    userType : 0
                }
            }
            dd.createKVManager(kvManagerConfig).then((manager) => {
                console.log("gyf dkvstore createKVManager success");
                that.kvm = manager;
                that.getStore()
            }).catch((err) => {
                console.log("gyf dkvstore createKVManager err: "  + JSON.stringify(err));
            });
        } catch (e) {
            console.log("gyf dkvstore An unexpected error occurred. Error:" + e);
        }
    },

//    根据扑克牌的index得出对应的数字
    getValue: function(num) {
        if (num >= 1 && num <=10) {
            return num;
        } else {
            //J,Q,K都按照1来计算
            return 1;
        }
    },
    getStore: function(){
        try {
            const options = {
                createIfMissing : true,
                encrypt : false,
                backup : false,
                autoSync : true,
                kvStoreType : 1,
                securityLevel : 3,
            };
            let that = this;
            this.kvm.getKVStore('testcoap', options).then((store) => {
                console.log("gyf dvkstore getKVStore success");
                that.kv = store;
                store.on('dataChange', 1, function (data) {
                    // {"deviceId":"","insertEntries":[],"updateEntries":[{"key":"time","value":{"type":5,"value":6199703}}],"deleteEntries":[]}
                    // {"deviceId":"","insertEntries":[],"updateEntries":[{"key":"result","value":{"type":0,"value":"shitou"}}],"deleteEntries":[]}
                    console.log("gyf dvkstore dataChange callback call data: " + JSON.stringify(data));

                    let result = data.updateEntries[0].value.value;
//                    let result = data.insertEntries[0].value.value;
                    //false代表不显示对方出的结果

                    if ("request" == result) {
                        //对方发来请求对战
                        that.title = "对方请求对战，请点击应答对战按钮";
                        that.displayimg = false;
                        that.result = "";
                        //gameOver置为false表示，游戏进行中，还没有任何乙方提交
                        that.gameOver = false;
                        console.log("dvkstore datachange request");
                    } else if (result.indexOf("response") >= 0) {
                        //对方发来应答对战,此时可以随机显示四张扑克牌
                        that.result = result;
                        var imgIndexList = result.split(",");
                        that.numList = [];
                        let img1Index = imgIndexList[1];
                        let img2Index = imgIndexList[2];
                        let img3Index = imgIndexList[3];
                        let img4Index = imgIndexList[4];
                        that.numList.push(that.getValue(img1Index));
                        that.numList.push(that.getValue(img2Index));
                        that.numList.push(that.getValue(img3Index));
                        that.numList.push(that.getValue(img4Index));
                        that.numList.sort(function (a,b) {return a-b;});

                        that.image1 = that.images[img1Index];
                        that.image2 = that.images[img2Index];
                        that.image3 = that.images[img3Index];
                        that.image4 = that.images[img4Index];

                        that.title = "对方应答对战，同步显示四张扑克牌";
                        that.displayimg = true;



                        console.log("dvkstore datachange response");
                    } else {
                        //对方提交结果
                        if (result.indexOf("success") >= 0) {
                            //游戏已经结束，弹出提示
                            prompt.showToast({
                                message: "对方正确答案已经输出，游戏结束",
                                duration: 3000,
                            });
                            that.gameOver = true;
                            that.title = "对方赢得比赛 " + result;
                        } else {
                            if (that.checkResult(result)) {
                                that.title = "对方结果正确，赢得比赛: " + result;
                            }
                        }
                    }
                });
                store.on('syncComplete', function (data) {
                    console.log("dvkstore syncComplete callback call data: " + data);
                });
            }).catch((err) => {
                console.log("dvkstore getKVStore err: "  + JSON.stringify(err));
            });
        } catch (e) {
            console.log("dvkstore An unexpected error occurred. Error:" + e);
        }
    },
    onclose: function(){
        if(this.kv == null){
//            this.data.title = 'open first';
            return;
        }
        this.kv = null;
        this.title = 'closed';
    },
    onput: function(){
        console.log("dvkstore onput");
//                this.title = 'begin to put.\n'
        if(this.kv == null){
            console.log("dvkstore onput kv == null");
            this.title = 'open first';
            return;
        }
        let that = this;
        this.kv.put('time', new Date().getTime()).then(()=>{
//            that.title += 'put ok';
        }).catch((err)=>{
            console.log("dvkstore onput catch error");
            console.log(err)
//            this.title = 'put err: '+JSON.stringify(err);
        })
    },
    onget: function(){
        console.log("dvkstore onget");
        if(this.kv == null){
            console.log("dvkstore onget kv == null");
//            this.title = 'open first';
            return;
        }

        let that = this;
        this.kv.get('time').then((data)=>{
            console.log('dvkstore get')
            console.log("dvkstore" + data)
            that.title = 'get ok: ' + JSON.stringify(data);
        }).catch((err)=>{
            console.log("dvkstore onget catch error");
            console.log(err)
        })
    },
    commit: function(){

        if (this.gameOver) {
            prompt.showToast({
                message: "正确答案已经输出，游戏已结束",
                duration: 3000,
            });
            return;
        }

        let cr = this.checkResult(this.commitStr);

        if (cr) {
            this.title = "我方提交了结果正确，赢得了比赛";
            //告诉对方，我方已经成功
            this.putmethod("success: " + this.commitStr);
        } else {
            prompt.showToast({
                message: "输入内容不正确，请重新输入",
                duration: 3000,
            });
        }

    },

    request: function(){
        //申请对战
        this.title = "我方申请对战";
        this.result = "request";
        this.displayimg = false;

        this.putmethod(this.result);
    },
    response: function() {

        //应答对战,此时可以随机显示四张扑克牌
        this.title = "我方应答对战，随机显示扑克牌";
        this.numList = [];
        let img1Index = this.getRandom(1,13);
        let img2Index = this.getRandom(1,13);
        let img3Index = this.getRandom(1,13);
        let img4Index = this.getRandom(1,13);
        this.numList.push(this.getValue(img1Index));
        this.numList.push(this.getValue(img2Index));
        this.numList.push(this.getValue(img3Index));
        this.numList.push(this.getValue(img4Index));
        this.numList.sort(function (a,b) {return a-b;});

        this.image1 = this.images[img1Index];
        this.image2 = this.images[img2Index];
        this.image3 = this.images[img3Index];
        this.image4 = this.images[img4Index];
        this.displayimg = true;

        //将随机的结果发送给对方
        this.result = "response," + img1Index + "," + img2Index + "," + img3Index + "," + img4Index;
        this.putmethod(this.result);

    },
    end: function(){
        this.onclose();
    },

    putmethod: function(str){
        if(this.kv == null){
            console.log("gyf dvkstore putmethod kv == null");
            return;
        }
        let that = this;
        this.kv.put('result', str).then(()=>{
           console.log("gyf put str = " + str);

        }).catch((err)=>{
            console.log("dvkstore putmethod catch error");
            console.log(err);
        })
    },

    change: function(e){
        console.log("gyf change value = " + e.value);
        this.result = e.value;
//        prompt.showToast({
//            message: "value: " + e.value,
//            duration: 3000,
//        });
    },

    zero: function() {
        this.commitStr += "0";
    },

    one: function() {
        this.commitStr += "1";
    },

    two: function() {
        this.commitStr += "2";
    },

    three: function() {
        this.commitStr += "3";
    },

    four: function() {
        this.commitStr += "4";
    },

    five: function() {
        this.commitStr += "5";
    },

    six: function() {
        this.commitStr += "6";
    },

    seven: function() {
        this.commitStr += "7";
    },

    eight: function() {
        this.commitStr += "8";
    },

    nine: function() {
        this.commitStr += "9";
    },

    plus: function() {
        this.commitStr += "+";
    },

    subtract: function() {
        this.commitStr += "-";
    },

    multiply: function() {
        this.commitStr += "*";
    },

    divide: function() {
        this.commitStr += "/";
    },

    parenthesesLeft: function() {
        this.commitStr += "(";
    },

    parentheseRight: function() {
        this.commitStr += ")";
    },

    clean: function() {
        this.commitStr = "";
    },


}



